//
//  YFSensorViewController.m
//  SquashSpark
//
//  Created by Coollang on 2017/11/8.
//  Copyright © 2017年 Coollang-YF. All rights reserved.
//

#import "YFSensorViewController.h"
#import "UserGroup.h"
#import "UserArrowItem.h"
#import "UserLabelItem.h"
#import "PNChart.h"
#import "YFSensorManager.h"
#import "YFSportAndSensorApi.h"
#import "NSString+Extension.h"
#import "YFAlertHelper.h"
#import "JCUpdateViewController.h"
#import "YFSearchController.h"
#import "YFMMDrawerStateManager.h"
#import "YFSensorAboutController.h"

#define kCenterViewWidth ((190 * kYFScreenWidth) / 375.0)

@interface YFSensorViewController ()
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIImageView *settingDeviceBgImg;
@property (weak, nonatomic) IBOutlet UIView *centerView;

@property (nonatomic, strong) PNCircleChart *progressView;
@property (weak, nonatomic) IBOutlet UILabel *centerLabel;
@property (weak, nonatomic) IBOutlet UIImageView *rotionImageView;
@property (weak, nonatomic) IBOutlet UIImageView *circleHightLightView;

@property (weak, nonatomic) IBOutlet UICountingLabel *batteryLabel;
@property (weak, nonatomic) IBOutlet UILabel *batteryUnitLabel;
@property (nonatomic, assign)BOOL stopRotation;

/** 定时器去读电量 */
@property (nonatomic, strong)NSTimer *timer;

/** 是否正在读取电量 */
@property (nonatomic, assign) BOOL isReadingBattery;

// 当前设备的电量
@property (nonatomic, assign)NSInteger currentBattery;

/** 是否关闭断开连接自动退到上一个页面 */
@property (nonatomic, assign) BOOL disconnectAutoPopVc;

@end

@implementation YFSensorViewController {
    BOOL _isCurrentView; // 是否在当前页面
}

+ (instancetype)sensorViewControllerWithType:(kSensorVCType)sensorVcType {
    YFSensorViewController *sensorVc = [[UIStoryboard storyboardWithName:@"Sensor" bundle:nil] instantiateViewControllerWithIdentifier:NSStringFromClass([self class])];
    sensorVc.sensorVcType = sensorVcType;
    return sensorVc;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.rotionImageView.hidden = YES;
    self.disconnectAutoPopVc = YES;
    self.title = @"My Spark";
    [self configuerUi];
    [self regiesterNotification];
    [self loadTableViewDataSource];
    [self updateSensorViewUiWithType:self.sensorVcType];
}
// 切换中心控制器
- (void)centerViewControllerChangeNoti:(NSNotification *)noti {
    if (![noti.object isEqual:self]) {
        [self.timer invalidate];
        self.timer = nil;
        _isCurrentView = NO;
    }
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    _isCurrentView = YES;
    if (self.sensorVcType != kSensorDeviceSetting) {
        if ([self chectBlueStateShowAlert:NO]) {
            // 去读电量
            self.sensorVcType = kSensorConnect;
//            [self timer];
        }else {
            self.sensorVcType = kSensorNoConnect;
        }
    }else {
        [self updateSensorViewUiWithType:self.sensorVcType];
    }
}


- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.timer invalidate];
    self.timer = nil;
    _isCurrentView = NO;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [[YFMMDrawerStateManager sharedManager].drawerController removeObserver:self forKeyPath:@"centerViewController"];
}
#pragma mark - 更新界面操作
- (void)setSensorVcType:(kSensorVCType)sensorVcType {
    _sensorVcType = sensorVcType;
    [self updateSensorViewUiWithType:sensorVcType];
}
- (void)configuerUi {
    self.centerLabel.font = kOpenSansFont(OpenSansRegular, 16.0);
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = kSeparationLineColor;
    self.progressView = [[PNCircleChart alloc] initWithFrame:CGRectMake(0, 0, kCenterViewWidth, kCenterViewWidth) total:@100 current:@0 clockwise:YES shadow:YES shadowColor:[UIColor colorWithWhite:1 alpha:0.4]];
    self.progressView.chartType = PNChartFormatTypeNone;
    self.progressView.strokeColor = kYellowGreenColor;
    self.progressView.lineWidth = @6;
    self.progressView.countingLabel.textColor = kTWhiteText;
    self.progressView.circle.lineCap = kCALineCapSquare;
    self.progressView.displayCountingLabel = NO;
    self.progressView.countingLabel.font = [UIFont boldSystemFontOfSize:15];
    [self.centerView addSubview:self.progressView];
    self.batteryLabel.format = @"%d";
    [self.progressView strokeChart];
}

- (void)updateSensorViewUiWithType:(kSensorVCType)type {
    [self loadTableViewDataSource];
    [self.tableView reloadData];
    self.centerView.hidden = (type == kSensorDeviceSetting);
    self.settingDeviceBgImg.hidden = (type != kSensorDeviceSetting);
   
    switch (type) {
        case kSensorConnect:{
            if (self.currentBattery <= 0) {
                self.centerView.layer.borderWidth = 0;
                self.stopRotation = NO;
                self.centerLabel.text = @"Reading Data...";
                [self checkUpadte];
            }else {
               [self timer];
            }
        }
            break;
        case kSensorNoConnect:{
            self.currentBattery = 0;
            [self.timer invalidate];
            self.timer = nil;
            [self.centerView clipsCornerRadius:kCenterViewWidth * 0.5 borderWidth:6 borderColor:kYellowGreenColor];
            [self.progressView updateChartByCurrent:0];
            self.progressView.hidden = YES;
            self.centerLabel.text = @"NOT CONNECTED";
            self.batteryLabel.text = @"";
            
            self.batteryUnitLabel.hidden = YES;
        }
            break;
        case kSensorDeviceSetting:{
            
        }
            break;
    }
}
// 检测升级
- (void)checkUpadte {
    __weak typeof(self)weakSelf = self;
    [[YFSensorManager shareSensorManager] checkSensorUpadteWithParent:self locationversion:^(BOOL versionSuccessful, NSString *version, NSInteger battery) {
        [self timer];
        if (versionSuccessful) {
           [weakSelf updateBetteryUIWithBattery:battery];
            [YFSportAndSensorApi getServerDeviceVersionWithOemTpe:[YFCommunicationManager shareInstance].lgPeripheral.oemType completed:^(NSString *versionS, NSString *downloadPath, NSError *error) {
                if (error == nil) {
                    // 判断版本号
                    if ([NSString isNeedUpgradeVersion:version targetVersion:versionS]) {
                        // 2. 判断电量
                        // 3.弹窗或直接点击升级
                        NSLog(@"有新固件");
                        [YFAlertHelper showAlertController:self
                                                     Title:@"Firmware Update"
                                                   message:[NSString stringWithFormat:@"Current firmware is：%@\nNew firmware version：%@",version,versionS]
                                               cancelTitle:@"Cancel"
                                              defalutTitle:@"Upgrade"
                                              cancelAction:nil
                                             defalutAction:^(UIAlertAction *action) {
                                                 [weakSelf goToUpgradeForFirmwarePath:downloadPath];
                        }];
                    }
                }
            }];
        }
    }];
}

- (void)goToUpgradeForFirmwarePath:(NSString *)firmwarePath{
    [self.timer invalidate];
    self.timer = nil;
    JCUpdateViewController *upvc = [[UIStoryboard storyboardWithName:@"Sensor" bundle:[NSBundle mainBundle]] instantiateViewControllerWithIdentifier:@"JCUpdateViewController"];
    upvc.firmwarePath = firmwarePath;
    upvc.manager = [YFCommunicationManager shareInstance].lgCenterManager.manager;
    upvc.peripheral = [YFCommunicationManager shareInstance].lgPeripheral.cbPeripheral;
    upvc.upgradeSuccess = ^{
        [[YFCommunicationManager shareInstance].lgCenterManager configureSetting];
    };
    [self presentViewController:upvc animated:YES completion:nil];
}

- (void)updateBattery {
    if (_isReadingBattery == NO && ![self chectBlueStateShowAlert:NO]) {
        return;
    }
    _isReadingBattery = YES;
    __weak typeof(self) weakSelf = self;
    [[YFSensorManager shareSensorManager] readBattery:^(BOOL success, NSInteger battery) {
        if (success) {
            [weakSelf updateBetteryUIWithBattery:battery];
        }else {
            weakSelf.stopRotation = YES;
            weakSelf.centerView.layer.borderWidth = 0;
            weakSelf.batteryUnitLabel.hidden = YES;
            [weakSelf.progressView setCurrent:@0];
            weakSelf.progressView.showProgressAni = YES;
            [weakSelf.progressView strokeChart];
            weakSelf.progressView.showProgressAni = NO;
            weakSelf.isReadingBattery = NO;
        }
    }];
}

- (void)updateBetteryUIWithBattery:(NSInteger)battery {
    if (battery > 0) {
        self.stopRotation = YES;
        self.centerView.layer.borderWidth = 0;
        self.currentBattery = battery;
        self.progressView.hidden = NO;
        if (battery / 100 == 0 || battery / 100 == 1) {
            [self.progressView setCurrent:@(battery)];
            self.batteryUnitLabel.hidden = NO;
            [self.batteryLabel countFrom:self.batteryLabel.text.integerValue to:battery];
            
            self.centerLabel.text = @"Remaining battery";
        }else if (battery == 120){
            [self.progressView setCurrent:@(battery)];
            self.batteryLabel.text = @"";
            self.centerLabel.text = @"Charging";
            self.batteryUnitLabel.hidden = YES;
            
        }
        
        [self.progressView strokeChart];
        self.progressView.showProgressAni = NO;
        self.isReadingBattery = NO;
    }
}

// 开始或停止旋转
- (void)setStopRotation:(BOOL)stopRotation {
    _stopRotation = stopRotation;
    self.rotionImageView.hidden = stopRotation;
    [self startRotaionImageView];
}

- (void)startRotaionImageView {
    if (self.stopRotation) {
        return;
    }
    __weak typeof(self) weakSelf = self;
    [UIView animateWithDuration:0.05 animations:^{
        weakSelf.rotionImageView.transform = CGAffineTransformRotate(weakSelf.rotionImageView.transform, M_PI_4/4);
    } completion:^(BOOL finished) {
        [weakSelf startRotaionImageView];
    }];
}
- (NSTimer *)timer {
    if (_timer == nil) {
        _timer = [NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(updateBattery) userInfo:nil repeats:YES];
    }
    return _timer;
}

#pragma mark - Notification
- (void)regiesterNotification {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deviceConnectHandel) name:kLGPeripheralDidConnect object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deviceDidDisconnectHandle) name:kLGPeripheralDidDisconnect object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(centerViewControllerChangeNoti:) name:kChangeCenterViewControllerNoti object:nil];
}
- (void)deviceConnectHandel {
    if (_isCurrentView && self.sensorVcType != kSensorDeviceSetting) {
        self.sensorVcType = kSensorConnect;
        self.progressView.showProgressAni = YES;
    }
}

- (void)deviceDidDisconnectHandle {
    if (self.sensorVcType != kSensorDeviceSetting) {
        self.sensorVcType = kSensorNoConnect;
    }else {
        if (self.disconnectAutoPopVc) {
            [self.navigationController popViewControllerAnimated:YES];
        }
    }
}
#pragma mark - 数据源
- (void)loadTableViewDataSource {
    __weak typeof(self) weakSelf = self;
    if (self.sensorVcType != kSensorDeviceSetting) {
        [self.groups removeAllObjects];
        UserGroup *group0 = [[UserGroup alloc] init];
        UserArrowItem *item0_0 = [UserArrowItem itemWithIcon:@"sensor_search" andTitle:@"Search For Sensor" andTarget:nil];
        [item0_0 setBlock:^(UserItem *itemT,NSIndexPath *indexPath) {
            if ([YFCommunicationManager shareInstance].isCentralReady && ![self chectBlueStateShowAlert:NO]) {
                // 弹出搜索框
                [YFSensorManager openSensorControllrWithVc:weakSelf isNecessaryOpenSensorVc:NO];
//                YFSearchController *searchVc = [[UIStoryboard storyboardWithName:@"Sensor" bundle:nil] instantiateViewControllerWithIdentifier:@"YFSearchController"];
//                searchVc.title = itemT.title;
//                [weakSelf.navigationController pushViewController:searchVc animated:YES];
            }
        }];
        
        UserArrowItem *item0_1 = [UserArrowItem itemWithIcon:@"sensor_setting" andTitle:@"Device Settings" andTarget:[UIViewController class]];
        
        [item0_1 setBlock:^(UserItem *itemT,NSIndexPath *indexPath) {
            if ([self chectBlueStateShowAlert:YES]) {
                if (itemT.cellState != kCellStateUnenable) {
                    YFSensorViewController *settingDeviceVc = [YFSensorViewController sensorViewControllerWithType:kSensorDeviceSetting];
                    settingDeviceVc.title = itemT.title;
                    [weakSelf.navigationController pushViewController:settingDeviceVc animated:YES];
                }
            }
        }];
        
        UserArrowItem *item0_2 = [UserArrowItem itemWithIcon:@"sensor_update" andTitle:@"Check For Updates" andTarget:[UIViewController class]];
        item0_2.cellState = kCellStateUnenable;
        [item0_2 setBlock:^(UserItem *itemT, NSIndexPath *indexpath) {
            if ([self chectBlueStateShowAlert:YES]) {
                [weakSelf checkUpadte];
            }
        }];
        
        UserItem *item0_3 = [UserItem itemWithIcon:@"sensor_about" andTitle:@"About Equipment"];
        item0_3.cellState = kCellStateUnenable;
        [item0_3 setBlock:^(UserItem *itemT, NSIndexPath *indexpath) {
            if ([self chectBlueStateShowAlert:YES]) {
                YFSensorAboutController *aboutVc = [[YFSensorAboutController alloc] init];
                [weakSelf.navigationController pushViewController:aboutVc animated:YES];
            }
        }];
        
        UserItem *item0_4 = [UserItem itemWithIcon:@"sensor_disconnect" andTitle:@"Disconnect"];
        [item0_4 setBlock:^(UserItem *itemT,NSIndexPath *indexPath) {
            if ([self chectBlueStateShowAlert:YES]) {
                [[YFSensorManager shareSensorManager] disconnect:YES callback:^(BOOL success) {
                    
                }];
            }
        }];
       
        [group0.items addObjectsFromArray:@[item0_0,item0_1,item0_2,item0_3,item0_4]];
        
        for (UserItem *item in group0.items) {
            item.cellState = self.sensorVcType == kSensorConnect ? kCellStateNormal:kCellStateUnenable;
        }
        
        if (self.sensorVcType == kSensorConnect) {
            [group0.items removeObject:item0_0];
        }else {
            [group0.items.firstObject setCellState:kCellStateNormal];
        }
        [self.groups addObject:group0];
    }else {
        [self loadSettingDecviceItems];
    }
}

// 设备设置
- (void)loadSettingDecviceItems {
    
    [self.groups removeAllObjects];
    
    __weak typeof(self) weakSelf = self;
    
    UserGroup *group0 = [[UserGroup alloc] init];
    // 获取当前的设备名
    NSString *deviceName = [YFCommunicationManager shareInstance].lgPeripheral.name;
    UserLabelItem *item0_0 = [UserLabelItem itemWithIcon:@"sensor_changeDeviceName" labelItemWithTitle:@"Device Name" andValue:deviceName];
    
    [item0_0 setBlock:^(UserItem *itemT,NSIndexPath *indexPath) {
        weakSelf.disconnectAutoPopVc = NO;
        [[YFSensorManager shareSensorManager] changeDeviceNameCallback:^(BOOL success, NSString *newName) {
            if (success) {
                // 刷新数据
                itemT.subTitle = newName;
                [weakSelf.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
            }
        }];
    }];
    
    UserItem *item0_1 = [UserItem itemWithIcon:@"sensor_cleanCache" andTitle:@"Clear Cache"];
    
    [item0_1 setBlock:^(UserItem *itemT,NSIndexPath *indexPath) {
        [[YFSensorManager shareSensorManager] cleanDeviceCache:^(BOOL success) {
            if (success) {
                [self.hud showSuccessWithStatus:@"Clean Successfully" dimissAfterSecond:1.5];
            }
        }];
    }];
    
    UserItem *item0_2 = [UserItem itemWithIcon:@"sensor_reset" andTitle:@"Reset"];
    
    [item0_2 setBlock:^(UserItem *itemT,NSIndexPath *indexPath) {
        
        [YFAlertHelper showTwoAlertController:self Title:@"Prompt" message:NSLocalizedString(@"Restoring factory settings will clear all device information and delete today's records. Continue?", nil) cancelTitle:@"Cancel" defalutTitle:@"Reset" defaultBtnStyle:UIAlertActionStyleDestructive cancelAction:^(UIAlertAction *action) {
            
        } defalutAction:^(UIAlertAction *action) {
            [[YFCommunicationManager shareInstance] requestOperationType:OperationTypeResetDevice parmaObject:nil completionBlock:^(BOOL success, id response, NSError *error) {
                if (success) {
                    [self.hud showSuccessWithStatus:@"Reset Successfully" dimissAfterSecond:1.5];
                }
            }];
        }];
    }];
    
    [group0.items addObjectsFromArray:@[item0_0,item0_1,item0_2]];
    [self.groups addObject:group0];
}

- (BOOL)chectBlueStateShowAlert:(BOOL)show {
    if (![YFCommunicationManager shareInstance].isPeripheralConnected) {
        // 弹框
        YFLog(@"你尚未连接硬件，请查找并连接手环以便进行设置操作");
        return NO;
    }
    return YES;
}



@end
